#include "log_Gen.h"

#include <QRegularExpression>
#include <QRegularExpressionMatch>

#include <QByteArray>


uint32_t Realtime_flag = 0;

QString logPath1;
QString logPath2;
QString logFileFullPath;
// 生成或插入 Log信息到文件
void Gen_Insert_LogFile(QString *outext,
                        QString filePath,
                        uint32_t id,
                        uint8_t *data,
                        uint16_t send_flag)
{

    QString  inesertTEXT;
    QDateTime Datetime = QDateTime::currentDateTime();

    QString  comText0  = Datetime.toString("yyyy-MM-dd HH:mm:ss.zzz") + ": ";
    QString  comText1  = "接收到数据:   ";
    const QString  comText2 = "帧ID:";
    QString comText3 ="0x" + QString::number(id,16).toUpper().rightJustified(8,'0',true) + " ";
    const QString  comText4 = "帧格式:数据帧 ";
    QString  comText5 = " 扩展帧 ";
    QString  comText6 = "时间戳:";
    QString  comText7 = Datetime.toString("yyyy-MM-dd HH:mm:ss") + " ";
    QString  comText8 = "数据:  "
                      +  QString::number(data[0],16).toUpper().rightJustified(2,'0',true)  + " " \
                      +  QString::number(data[1],16).toUpper().rightJustified(2,'0',true)  + " " \
                      +  QString::number(data[2],16).toUpper().rightJustified(2,'0',true)  + " " \
                      +  QString::number(data[3],16).toUpper().rightJustified(2,'0',true)  + " " \
                      +  QString::number(data[4],16).toUpper().rightJustified(2,'0',true)  + " " \
                      +  QString::number(data[4],16).toUpper().rightJustified(2,'0',true)  + " " \
                      +  QString::number(data[6],16).toUpper().rightJustified(2,'0',true)  + " " \
                      +  QString::number(data[7],16).toUpper().rightJustified(2,'0',true)  + " ";

    if(send_flag == 0)
    {
        comText1  = "接收到数据:   ";
    }
    else
    {
       comText1  = "发送的数据:   ";
    }


    // 以下创建日志文件
    QString QStr_Date = QDate::currentDate().toString("yyyy-MM-dd");
    QString realPath = filePath  + QStr_Date + ".log";
    QDir dir(QFileInfo(realPath).absoluteDir()); //检查log目录
    if(!dir.exists())
    {
        if(!dir.mkpath("."))
        {
           qDebug()<<"无法创建目录"<<dir.absolutePath();
           return;
        }
    }

    QFile logfile(realPath); //检查文件
    if(!logfile.open(QIODevice::WriteOnly|QIODevice::Append|QIODevice::Text))
    {
        if(!logfile.open(QIODevice::WriteOnly|QIODevice::Text))
        {
            qDebug()<<"新建文件失败";
            return;
        }
    }

    inesertTEXT =  comText0 + comText1 + comText2 + comText3 + comText4
                 + comText5 + comText6 + comText7 + comText8;

    *outext = inesertTEXT;

    QTextStream out(&logfile);
    out<<inesertTEXT<<"\n";
    logfile.close();
}


// 从log文件中读取指定的一行报文
// 读取到的文本保存到textLine
int32_t  Read_Loginfo_fromFile(QString FilePath,QString *textLine, uint32_t lineNUm,qint64  *filePosition)
{

    if (textLine == nullptr || filePosition == nullptr)
    {
        qDebug() << "textLine or filePosition pointer is NULL";
        return -1;
    }

    QFile logfile(FilePath); //检查文件
    if (!logfile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "打开log文件失败";
        return -1;
    }
    QTextStream in(&logfile);
    uint32_t i = 0;


    // 移动文件指针到指定的位置
    if (!in.seek(*filePosition))
    { // 如果需要从当前位置开始读取，使用*filePosition
        qDebug() << "无法移动到指定位置";
        logfile.close();
        return -1;
    }


    for (i = 0; i < lineNUm; i++)
    {
        if(in.atEnd() == false)
        {
            textLine[i] = in.readLine();
            if (textLine[i].isEmpty())
            { // 检查是否为空字符串
                break;
            }
            *filePosition = in.pos(); // 记录文件指针位置
        }
        else
        {
            break;
        }
    }
    logfile.close();
    return i; // 返回实际读取的行数
}



// 使用通配符完成解析功能
bool parseLogLine(const QString &line, S_LogEntry &entry)
{
    QRegularExpression regex(
        R"((\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})\s*:\s*(发送的|接收到)数据\s*:\s*帧ID\s*:\s*(0x[0-9a-fA-F]+) \s*帧格式\s*:\s*(数据帧|远程帧) \s*扩展帧? \s*时间戳\s*:\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \s*数据\s*:\s*([0-9a-fA-F ]+))",
        QRegularExpression::DotMatchesEverythingOption);
    QRegularExpressionMatch match = regex.match(line);

    if (match.hasMatch())
    {
        entry.timestamp =  QDateTime::fromString(match.captured(1), "yyyy-MM-dd HH:mm:ss.zzz");
        entry.frameId = match.captured(3).mid(2).toULong(0, 16);
        entry.frameFormat = (match.captured(4) == "数据帧") ? 1 : 2;
        entry.isExtendedFrame = (match.captured(4) == "扩展帧");
        entry.dataTimestamp = QTime::fromString(match.captured(5).mid(11, 8), "HH:mm:ss");

        QByteArray hexData = match.captured(6).toLocal8Bit();
        QByteArray binData = QByteArray::fromHex(hexData);
        if (binData.size() >= 8)
        {
            // Copy the first 8 bytes into the data array
            for (int i = 0; i < 8; ++i)
            {
                entry.data[i] = binData[i];
            }
        }
        else
        {
            // Handle the case where the data is less than 8 bytes
            memset(entry.data, 0, 8); // Clear the data array
            int copySize = qMin(binData.size(), 8);
            memcpy(entry.data, binData.constData(), copySize);
        }
        return true;
    }
    return false;
}


